//
//  HomeController.m
//  GBKHouse
//
//  Created by XMYY-19 on 2017/8/30.
//  Copyright © 2017年 XMYY-19. All rights reserved.
//

#import "HomeController.h"
#import "Global1.h"
//#import "Common.h"
#import "Masonry.h"
#import "NewEquipment.h"
#import "LeftCollectionCell.h"
#import "RightCollectionViewCell.h"
#import "LampController.h"
#import "eventAction.h"
#import "CurtainsController.h"
#import "NewTVController.h"
#import "AppDelegate.h"
#import "GKBEquipmentsManager.h"

#define PIC_WIDTH 200
#define PIC_HEIGHT 200
#define COL_COUNT 3

#define SFdentifiter  @"cellId"

#define SFdentifited1 @"cellIds"
@interface HomeController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)NSMutableArray *dataSourceArr;

@property(nonatomic,strong)NSMutableArray *rightSouceArr;
@property(nonatomic,strong)NSMutableArray *allStatesM;
@property(nonatomic,strong)NewEquipment *myNewEqu;
@property(nonatomic,strong)NSArray *MyArrs;
@property(nonatomic,strong)LeftCollectionCell *cell;
@property(nonatomic,strong)LeftCollectionCell *leftCell;
@property(nonatomic,strong)UISegmentedControl *mySegment;
@property(nonatomic,assign)BOOL allOpen;
@property(nonatomic,assign)BOOL allClose;
@end

@implementation HomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"mainbg"]];
    
    UIImage *image = [UIImage imageNamed:@"mainbg"];
    self.view.layer.contents = (id)image.CGImage;
    _allOpen = NO;
    _allClose = NO;
    
    
    self.roomNames = [NSMutableArray array];
    self.rooms = [NSMutableDictionary dictionary];
    self.roomNamess = [NSMutableArray array];
    self.roomss = [NSMutableDictionary dictionary];
    self.sceneArray = [NSMutableArray array];
    self.areaEquipments = [NSMutableArray array];
    self.equipments = [NSMutableArray array];
    self.protectArray = [NSMutableArray array];
    
    self.allStatesM = [NSMutableArray array];
    
    //    self.tableViewArr =[NSMutableArray array];
    //
    //
    //    self.collectionArr =[NSMutableArray array];
    [self setTableViewHeaderView];
    
    [self initChangeDevice];
    
    // [self addAllButtons];
    [self initLeftCollectionView];
    
    [self initRightCollectionView];
    
    self.dataSourceArr =[[NSMutableArray alloc] init];
    
    self.rightSouceArr =[NSMutableArray array];
    
    [self equipmentState:^{
        [self loadList];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [self.rightSouceArr removeAllObjects];
    [self.rightSouceArr addObjectsFromArray:[[[GKBEquipmentsManager shareInstance] getEquipmentsArray] copy]];
    [self.rightSouceArr addObjectsFromArray:appDelegate.rightArray];
    if (self.rightSouceArr.count) {
        [self.rightCollectionView reloadData];
    }
}

- (void)loadList
{
    [self areaEquipmentList];
    [self equipmentList];
}

- (void)equipmentState:(void(^)(void))endresult
{
    NSString *refresh = @"2";
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\",\"refresh\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, refresh];
    [WebServices requestSynStartOrder:@"getEquipmentState" body:body result:^(NSDictionary *dic) {
        NSNumber *result = [dic objectForKey:@"result"];
        NSArray *states = [dic objectForKey:@"states"];
        if (result.integerValue == 0) {
            [self.allStatesM removeAllObjects];
            [self.allStatesM addObjectsFromArray:states];
        }
        if(endresult)
        {
            endresult();
        }
    }];
    
}

#pragma mark - 区域数据
- (void)areaEquipmentList
{
    
    NSString *sessionId = [LoginController1 sessionID];
    
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"getRelevanceHosts" body:body target:self action:@selector(areaEquipmentListEnd:) errorTip:errorType];
}

#pragma mark - 电器设备数据
- (void)equipmentList
{
    NSInteger sortType = [SystemSettting sortType];
    NSString *sessionId = [LoginController1 sessionID];
    
    NSString *fomat = @"[{\"sessionId\":\"%@\", \"obway\":\"%d\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, sortType];
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"getEquipmentList" body:body target:self action:@selector(equipmentListEnd:) errorTip:errorType];
}

- (void)equipmentListEnd:(NSDictionary *)dic
{
    NSLog(@"equipmentListEnd：%@", dic);
    // NSString *result = [dic objectForKey:@"result"];
    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *data = [dic objectForKey:@"data"];
    //    self.equipments = data;
    if (self.equipments) {
        [self.equipments removeAllObjects];
    }
    else
    {
        self.equipments = [[NSMutableArray alloc] init];
        
    }
    self.equipments = data;
    if ([data count]>0) {
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dic in data) {
            NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [array addObject:mutDic];
        }
        self.equipments = array;
    }
    //    NSLog(@"%@,%@", result, sessionId);
    [self.roomNames removeAllObjects];
    [self.rooms removeAllObjects];
    [self.protectArray removeAllObjects];
    if (result.integerValue == 0)
    {
        NSString *version = [dic objectForKey:@"version"];
        if (version && [version isEqualToString:@"ds"]) {
            //ds:  此主机有定时功能 de:  此主机为默认旧主机，没有定时功能
            // [SettingController setHaveTimeSetting:YES];
        }
        else{
            // [SettingController setHaveTimeSetting:NO];
        }
        NSString *saveEqusFile = [AppFile documentsPath:@"euqs.bat"];
        [dic writeToFile:saveEqusFile atomically:YES];
        for (NSDictionary *equ in data) {
            NSString *name = [equ objectForKey:@"name"];
            NSString *type = [equ objectForKey:@"type"];
            NSString *switchId = [equ objectForKey:@"switchId"];
            NSString *tagName = [equ objectForKey:@"tagName"];
            
            //            NSString *sting = [NSString stringWithCString:tagName.UTF8String encoding:NSUTF8StringEncoding];
            //            NSLog(@"r:%@",sting);
            
            NSString *regulate = [equ objectForKey:@"regulate"];
            NewEquipment *equipment = [[NewEquipment alloc]init];
            [equipment setName:name];
            [equipment setType:type];
            [equipment setSwitchId:switchId];
            [equipment setTagName:tagName];
            [equipment setRegulate:regulate];
            [equipment setState:[self initEquipmentsState:switchId]];
            
            if ([type isEqualToString:@"9"]) {//安防
                [self.protectArray addObject:equipment];
            }
            else
            {
                NSMutableArray *room = [self.rooms objectForKey:tagName];
                if (room) {
                    [room addObject:equipment];
                }
                else
                {
                    [self.roomNames addObject:tagName];
                    NSMutableArray *room = [[NSMutableArray alloc]init];
                    [room addObject:equipment];
                    [self.rooms setObject:room forKey:tagName];
                    [room release];
                }
            }
            
            [equipment release];
            
        }
        
        AppDelegate *appdelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
        appdelegate.curRooms = [self.rooms copy];
        
        [[GKBEquipmentsManager shareInstance] setCurRooms:[self.rooms copy]];
        
        [self getUserCameraList:^{
            [_houseArray removeAllObjects];
            [self initRoomsMenu];
        }];
    }
    else
    {
        NSString *errorType = [OperationTip errorType:ErrorTypeServerReturnFail];
        [iToast showTip:errorType gravity:iToastGravityBottom];
    }
    
}

- (NSString *)initEquipmentsState:(NSString *)switchId{
    for (NSDictionary *item in self.allStatesM) {
        NSString *curSwitchId = [item objectForKey:@"switchId"];
        if ([curSwitchId isEqualToString:switchId]) {
            return [item objectForKey:@"state"];
        }
    }
    return nil;
}

#pragma mark - 摄像头数据
- (void)getUserCameraList:(void(^)(void))endresult
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    // [WebServices setShowConnectting:NO];//关闭提示
    [WebServices requestSynStartOrder:@"getUserCameraList" body:body result:^(NSDictionary *dic) {
        [WebServices setShowConnectting:NO];
        NSNumber *result = [dic objectForKey:@"result"];
        if (result.integerValue == 0) {
            NSArray *data = [dic objectForKey:@"cameraGroup"];
            if (data) {
                self.cameraGroup = [NSMutableArray arrayWithArray:data];
            }
        }
        if (endresult) {
            endresult();
        }
    }];
}

- (void)initRoomsMenu
{
    [self.dataSourceArr removeAllObjects];
    for (NSString *key in self.roomNames)
    {
        NSLog(@"%@---", key);
        [self.dataSourceArr addObject:key];
    }
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.leftArray = [self.dataSourceArr mutableCopy];
    
    [[GKBEquipmentsManager shareInstance]setAreaArray:[self.dataSourceArr copy]];
    
    [self getAllData];
    [self.leftCollectionView reloadData];
}

//获取所有数据
-(void)getAllData
{
    [self.rightSouceArr removeAllObjects];
    for(id s in self.rooms)
    {
        NSArray *arr = self.rooms[s];
        for(int i=0;i<arr.count;i++)
        {
            NewEquipment *newModel = arr[i];
            self.myNewEqu = newModel;
            [self.rightSouceArr addObject:newModel];
        }
    }
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.rightArray = [self.rightSouceArr copy];
    
    [[GKBEquipmentsManager shareInstance] setEquipmentsArray:[self.rightSouceArr copy]];
    
    [self.rightCollectionView reloadData];
    
}

- (void)areaEquipmentListEnd:(NSDictionary *)dic
{
    
    NSLog(@"equipmentListEnd：%@", dic);
    //     NSString *result = [dic objectForKey:@"result"];
    //    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *data = [dic objectForKey:@"relevanceHosts"];
    //    NSLog(@"data主机名称＝＝＝＝%@",data);
    if (self.areaEquipments) {
        [self.areaEquipments removeAllObjects];
    }
    else
    {
        self.areaEquipments = [[NSMutableArray alloc] init];
    }
    for (NSDictionary *equ in data) {
        NSString *displayName = [equ objectForKey:@"displayName"];
        NSString *orderId = [equ objectForKey:@"orderId"];
        NSString *relevanceUserName = [equ objectForKey:@"relevanceUserName"];
        NSString *relevanceUserPass = [equ objectForKey:@"relevanceUserPass"];
        NSString *hostnum = [equ objectForKey:@"relevanceHostnum"];
        //        NSLog(@"主机名称＝＝＝＝%@",relevanceUserName);
        //        NSString *regulate = [equ objectForKey:@"regulate"];
        NewEquipment *equipment = [[NewEquipment alloc]init];
        [equipment setName:displayName];
        [equipment setOrderId:orderId];
        [equipment setRelevanceUserName:relevanceUserName];
        [equipment setRelevanceUserPass:relevanceUserPass];
        [equipment setType:@"14"];
        //        [equipment setRegulate:regulate];
        [equipment setState:kStateOFF];
        [equipment setSwitchId:hostnum];
        equipment.target = self;
        //        equipment.selector = @selector(openAreaInfo:);
        if ([hostnum isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"hostnum"]]) {
            [self.areaEquipments insertObject:equipment atIndex:0];
        }else{
            [self.areaEquipments addObject:equipment];
        }
        [equipment release];
    }
    //    [self refreshDevicesState];
    
    //    [self.areaEquipments release];
}

-(void)setTableViewHeaderView {
    
    //将navigationBar的背景设为透明
    
    [self.navigationController.navigationBar setBackgroundColor:[UIColor clearColor]];
    //去掉navigationBar下面的那条分割线
    //    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsCompact];
    self.navigationController.navigationBar.hidden = YES;
    CGFloat headerViewHeight = kFONT_SIZE_FROM_PX_VALUE(500);
    UIView* headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWide , headerViewHeight)];
    UIImageView* imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"pic_banner"]];
    //这个-64非常关键
    imgView.frame = CGRectMake(0, -64, screenWide, headerViewHeight + 64);
    
    [headerView addSubview:imgView];
    UILabel *myLable =[[UILabel alloc] initWithFrame:CGRectMake(0, 120, kScreenWidth, 100)];
    [myLable setTextColor:[UIColor whiteColor]];
    [myLable setText:@"GBK HOME"];
    myLable.textAlignment = NSTextAlignmentCenter;
    
    [imgView addSubview:myLable];
    
    [self.view addSubview:headerView];
}


/**
 初始化切换设备
 */
-(void)initChangeDevice
{
    NSArray *segmnetArr =[NSArray arrayWithObjects:@"场景",@"设备",nil];
    _mySegment =[[UISegmentedControl alloc] initWithItems:segmnetArr];
    _mySegment.frame = CGRectMake((SCREEN_WIDTH-190)/2, 260, 190, 25);
    _mySegment.selectedSegmentIndex = 0;
    _mySegment.tintColor =[UIColor colorWithRGBColorByString:@"#7ecef4"];
    [_mySegment addTarget:self action:@selector(indexDidChangeForSegmentedControl:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:_mySegment];
}

-(void)indexDidChangeForSegmentedControl:(UISegmentedControl *)sender
{
    //我定义了一个 NSInteger tag，是为了记录我当前选择的是分段控件的左边还是右边。
    NSInteger selecIndex = sender.selectedSegmentIndex;
    switch(selecIndex){
        case 0:
            //            leftTable.hidden = NO;
            //            rightTable.hidden = YES;
            sender.selectedSegmentIndex=0;
            //            tag = 0;
            //            [leftTable reloadData];
            self.rightCollectionView.hidden = YES;
            self.leftCollectionView.hidden = NO;
            break;
            
        case 1:
            //            leftTable.hidden = YES;
            //            rightTable.hidden = NO;
            sender.selectedSegmentIndex = 1;
            self.leftCollectionView.hidden = YES;
            self.rightCollectionView.hidden = NO;
            //            tag=1;
            //          [rightTable reloadData];
            //[self getAllData];
            break;
            
        default:
            break;
    }
}

-(void)initLeftCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    if (IS_IPAD) {
        layout.itemSize = CGSizeMake(160, 160);
    } else {
        layout.itemSize = CGSizeMake(100, 100);
    }
    self.leftCollectionView  =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 250+50,screenWide, 300) collectionViewLayout:layout];
    self.leftCollectionView.backgroundColor =[UIColor clearColor];
    
    
    [self.view addSubview:self.leftCollectionView];
    
    self.leftCollectionView.hidden = NO;
    
    [self.leftCollectionView registerClass:[LeftCollectionCell class] forCellWithReuseIdentifier:SFdentifiter];
    self.leftCollectionView.dataSource = self;
    self.leftCollectionView.delegate = self;
}

-(void)initRightCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    if (IS_IPAD) {
        layout.itemSize = CGSizeMake(160, 160);
    } else {
        layout.itemSize = CGSizeMake(100, 100);
    }
    self.rightCollectionView  =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 295,screenWide, SCREEN_HEIGHT-self.mySegment.bottom-60) collectionViewLayout:layout];
    self.rightCollectionView.backgroundColor =[UIColor clearColor];
    
    
    [self.view addSubview:self.rightCollectionView];
    
    
    self.rightCollectionView.hidden = YES;
    
    [self.rightCollectionView registerClass:[LeftCollectionCell class] forCellWithReuseIdentifier:SFdentifited1];
    self.rightCollectionView.dataSource = self;
    self.rightCollectionView.delegate = self;
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(collectionView==_leftCollectionView)
    {
        //        return self.dataSourceArr.count;
        return 2;//目前只有全开 全关
    }
    else
    {
        return self.rightSouceArr.count;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView==_leftCollectionView)
    {
        LeftCollectionCell *cell =(LeftCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:SFdentifiter forIndexPath:indexPath];
        self.leftCell = cell;
        //        NSString *nameStr =   [self.dataSourceArr objectAtIndex:indexPath.row];
        NSString *nameStr = @"";
        if (indexPath.row == 0) {
            nameStr = @"全开";
        } else {
            nameStr = @"全关";
        }
        cell.nameStr = nameStr;
        [self setPicUrlByModelName:nameStr];
        return cell;
    } else {
        LeftCollectionCell *cell =(LeftCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:SFdentifited1 forIndexPath:indexPath];
        self.cell = cell;
        NewEquipment *model =   [self.rightSouceArr objectAtIndex:indexPath.row];
        cell.nameLabel.text = model.name;
        [self setImageByModel:model ArrM:self.allStatesM];
        cell.nameLabel.font =[UIFont systemFontOfSize:kFONT_SIZE_FROM_PX_VALUE(24)];
        cell.nameLabel.textColor =[UIColor colorWithRGBColorByString:@"#c2e6f9"];
        return cell;
    }
}

-(void)setPicUrlByModelName:(NSString *)name
{
    if([name isEqualToString:@"会议室"])
    {
        self.leftCell.picImage.image =[UIImage imageNamed:@"huiyishi_bg"];
    }
    else if([name isEqualToString:@"花园"])
    {
        self.leftCell.picImage.image =[UIImage imageNamed:@"huayuan_bg"];
    }
    else if([name isEqualToString:@"接待室"])
    {
        self.leftCell.picImage.image =[UIImage imageNamed:@"jiedaishi_bg"];
    }
    else if([name isEqualToString:@"前台"])
    {
        self.leftCell.picImage.image= [UIImage imageNamed:@"qiantai_bg"];
    }
    else if ([name isEqualToString:@"全开"]) {
        if (_allOpen) {
            self.leftCell.picImage.image =[UIImage imageNamed:@"icon_kaiguan_on"];
        } else {
            self.leftCell.picImage.image =[UIImage imageNamed:@"icon_kaiguan"];
        }
    } else if([name isEqualToString:@"全关"]){
        if (_allClose) {
            self.leftCell.picImage.image =[UIImage imageNamed:@"icon_kaiguan_on"];
        } else {
            self.leftCell.picImage.image =[UIImage imageNamed:@"icon_kaiguan"];
        }
    }
}

-(void)setImageByModel:(NewEquipment *)model ArrM:(NSMutableArray *)ArrM
{
    BOOL isOpen = [model.state isEqualToString:@"1"];
    if(true)
    {
        switch ([model.type integerValue]) {
            case 1:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_dengguan_on"];
                } else {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_light"];
                }
                break;
            case 2:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_kongtiao_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_kongtiao_off"];
                }
                break;
            case 3:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_tv_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_tv"];
                }
                break;
            case 4:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_dvd_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_dvd"];
                }
                break;
            case 5:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_chuanglian_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_chuanglian"];
                }
                break;
                //                case 6:
                //                    break;
                //                case 7:
                //                    break;
            case 8:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_qita_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_qita_off"];
                }
                break;
            case 9:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_anfang_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_anfang"];
                }
                break;
            case 10:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_music_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_music_off"];
                }
                break;
                //                case 11:
                //                    break;
                //                case 12:
                //                    break;
                //                case 20:
                //                    break;
                //                case 21:
                //                    break;
                //                case 22:
                //                    break;
                //                case 23:
                //                    break;
                //                case 24:
                //                    break;
                //                case 25:
                //                    break;
            default:
                if(isOpen)
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_qita_on"];
                }
                else
                {
                    _cell.picImage.image =[UIImage imageNamed:@"icon_qita_off"];
                }
                break;
        }
    }
}


//首页中场景和设备的点击跳转函数
#pragma mark --首页中场景和设备的点击跳转函数 UICollectionView delegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _rightCollectionView) {
        NewEquipment *model =   [self.rightSouceArr objectAtIndex:indexPath.row];
        [self getNextPageByModel:collectionView equipment:model didSelectItemAtIndexPath:indexPath];
    } else {
        [self getNextPageByModel:collectionView equipment:nil didSelectItemAtIndexPath:indexPath];
    }
}

-(void)getNextPageByModel:(UICollectionView *)collectionView equipment:(NewEquipment *)model didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _rightCollectionView) {
        [self setEquipmentsState:model didSelectItemAtIndexPath:indexPath];
    } else {
        [self setALLEquipmentsState:model didSelectItemAtIndexPath:indexPath];
    }
}

-(void)setEquipmentsState:(NewEquipment *)model didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    switch ([model.type intValue]) {
        case 1://灯
            //0为不调   1为可调
            if([model.regulate intValue]==1)
            {
                [self.navigationController pushViewController:[[LampController alloc] initWithEquipment:model] animated:YES];
                self.navigationController.navigationBar.hidden = NO;
                [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsCompact];
                self.navigationController.navigationBar.layer.masksToBounds = YES;
            }
            else if([model.regulate intValue]==0)            //不可调
            {
                [self switchCtrl:model];
            }
            break;
        case 2://空调
            //0为不调   1为可调
            if([model.regulate intValue]==1)
            {
                [self.navigationController pushViewController:[[AirconditionController alloc] initWithEquipment:model] animated:YES];
            }
            //不可调
            else if([model.regulate intValue]==0)
            {
                [self switchCtrl:model];
            }
            break;
        case 3://
            //0为不调   1为可调
            if([model.regulate intValue]==1)
            {
                [self.navigationController pushViewController:[[NewTVController alloc] initWithEquipment:model] animated:YES];
            }
            //不可调
            else if([model.regulate intValue]==0)
            {
                [self switchCtrl:model];
            }
            break;
        case 5://窗帘
            //0为不调   1为可调
            if([model.regulate intValue]==1)
            {
                [self.navigationController pushViewController:[[CurtainsController alloc] initWithEquipment:model] animated:YES];
            }
            //不可调
            else if([model.regulate intValue]==0)
            {
                [self switchCtrl:model];
            }
            break;
        case 10:
            [self.navigationController pushViewController:[[MusicController alloc] initWithEquipment:model]animated:YES];
            break;
        default:
            [self switchCtrl:model];
            break;
    }
}

-(void)setALLEquipmentsState:(NewEquipment *)model didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0://开
            _allOpen = YES;
            _allClose = !_allOpen;
            [self switchAllCtrl:YES];
            break;
        case 1://关
            _allClose = YES;
            _allOpen = !_allClose;
            [self switchAllCtrl:NO];
            break;
        default:
            break;
    }
}

- (void)switchCtrl:(NewEquipment *)model{
    BOOL equipmentState;
    if ([model.state integerValue] == 1) {//on
        equipmentState = NO;
    } else {
        equipmentState = YES;
    }
    __weak typeof(self) weakSelf = self;
    [eventAction electricCompantWithOrder:equipmentState swtichId:model.switchId result:^(NSDictionary *dic) {
        [self ctlDeviceEnd:dic model:model];
        NSLog(@"ctlDevice block返回:%@",dic);
        __strong __typeof(&*weakSelf)strongSelf = weakSelf;
        //        NSLog(@"old:%@",strongSelf.rightSouceArr);
        for(int i=0;i<strongSelf.rightSouceArr.count;i++)
        {
            NSString *modelSwitchID = model.switchId;
            NewEquipment *item = strongSelf.rightSouceArr[i];
            NSString *arrSwitchID = item.switchId;
            BOOL isA = [modelSwitchID isEqualToString:arrSwitchID];
            if(isA)
            {
                if ([item.state integerValue]== 1) {
                    item.state = @"2";
                    [strongSelf.rightSouceArr replaceObjectAtIndex:i withObject:item];
                } else {
                    item.state = @"1";
                    [strongSelf.rightSouceArr replaceObjectAtIndex:i withObject:item];
                }
                break;
            }
        }
        [self.rightCollectionView reloadData];
        
        AppDelegate *appdelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
        appdelegate.rightArray = [self.rightSouceArr copy];
        
        [[GKBEquipmentsManager shareInstance] setEquipmentsArray:[strongSelf.rightSouceArr copy]];
    }];
}

- (void)ctlDeviceEnd:(NSDictionary *)dic model:(NewEquipment *)model
{
    if (model == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
    NSString *tip = @"";
    BOOL OPEN = [DeviceView deviceStateOn:model];
    BOOL STATE = !OPEN;
    NSNumber *result = [dic objectForKey:@"result"];
    if (result.integerValue == 0) {
        
        tip = [OperationTip operat:model.name open:STATE result:YES errorType:ErrorTypeServerReturnFail];
        [self setDeviceOn:STATE];
        
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNet];
    } else {
        tip = [OperationTip operat:model.name open:STATE result:NO errorType:ErrorTypeServerReturnFail];
    }
    
    [iToast showTip:tip gravity:iToastGravityBottom];
}

- (void)setDeviceOn:(BOOL)on
{
}

- (void)switchAllCtrl:(BOOL)equipmentState{
    [eventAction electricAllCompantWithOrder:equipmentState swtichId:@"1" result:^(NSDictionary *dic) {
        NSLog(@"ctlDevice block返回:%@",dic);
        if (equipmentState) {
            [self ctlDeviceInfo:dic tipName:@"操作成功，全开"];
        } else {
            [self ctlDeviceInfo:dic tipName:@"操作成功，全关"];
        }
        
        [self resetEquipmentsMemory:equipmentState];
        [self.leftCollectionView reloadData];
        [self.rightCollectionView reloadData];
    }];
}

- (void)resetEquipmentsMemory:(BOOL)isOpen{
    NSMutableArray *tempEquipmentArray = [NSMutableArray new];
    if (isOpen) {
        for (NSDictionary *equipment in self.allStatesM) {
            [equipment setValue:@"1" forKey:@"state"];
            [tempEquipmentArray addObject:equipment];
        }
    } else {
        for (NSDictionary *equipment in self.allStatesM) {
            [equipment setValue:@"2" forKey:@"state"];
            [tempEquipmentArray addObject:equipment];
        }
    }
    [self.allStatesM removeAllObjects];
    [self.allStatesM addObjectsFromArray:[tempEquipmentArray copy]];
    
}

- (void)ctlDeviceInfo:(NSDictionary *)dict tipName:(NSString *)tipName
{
    NSString *tip = @"";
    NSNumber *result = [dict objectForKey:@"result"];
    if (result.integerValue == 0) {
        
        tip = tipName;
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNet];
    }
    else
    {
        tip = tipName;
    }
    
    [iToast showTip:tip gravity:iToastGravityBottom];
}

@end
